﻿using System;

namespace Polynomials
{
    class Polynomials
    {
        static void PrintResult(decimal[] result)
        {
            for (int index = result.Length - 1; index >= 0; index--)
            {
                Console.Write("{0} ", result[index]);
            }
            Console.WriteLine();
        }

        static decimal[] GetArray(decimal[] first, decimal[] second, bool biggest = false)
        {
            if (biggest)
            {
                return first.Length > second.Length ? first : second;
            }

            return first.Length > second.Length ? second : first;
        }

        static decimal[] AddingSubtraction(decimal[] firstPolynomial, decimal[] secondPolynomial, bool adding = true)
        {
            decimal[] biggestPolynomial = GetArray(firstPolynomial, secondPolynomial, biggest: true);
            decimal[] smallestPolynomial = GetArray(firstPolynomial, secondPolynomial);
            decimal[] result = new decimal[biggestPolynomial.Length];

            for (int index = 0, length = smallestPolynomial.Length; index < length; index++)
            {
                result[index] = adding ? biggestPolynomial[index] + smallestPolynomial[index]
                                       : firstPolynomial[index] - secondPolynomial[index];
            }

            if (biggestPolynomial.Length != smallestPolynomial.Length)
            {
                int startIndex = smallestPolynomial.Length;
                Array.Copy(biggestPolynomial, startIndex, result, startIndex, biggestPolynomial.Length - startIndex);
            }

            return result;
        }

        static decimal[] Multiply(decimal[] firstPolynomial, decimal[] secondPolynomial)
        {
            decimal[] result = new decimal[firstPolynomial.Length + secondPolynomial.Length - 1];

            for (int indexFirstPol = 0, firstLength = firstPolynomial.Length; indexFirstPol < firstLength; indexFirstPol++)
            {
                for (int indexSecondPol = 0, secondLength = secondPolynomial.Length; indexSecondPol < secondLength; indexSecondPol++)
                {
                    result[indexFirstPol + indexSecondPol] += firstPolynomial[indexFirstPol] * secondPolynomial[indexSecondPol];
                }
            }

            return result;
        }

        static void Main()
        {
            decimal[] a = { -3, 1, 3 };
            decimal[] b = { 1, 1, 1, 1 };

            decimal[] resultAdded = AddingSubtraction(a, b);
            decimal[] resultSubstraction = AddingSubtraction(a, b, adding: false);
            decimal[] resultMultiply = Multiply(a, b);

            Console.Write("Sum: ");
            PrintResult(resultAdded);
            Console.Write("Substracted: ");
            PrintResult(resultSubstraction);
            Console.Write("Multipy: ");
            PrintResult(resultMultiply);
        }
    }
}
